package com.xunlai.infra.permission.manager.authority.login;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liang
 * @date 9/3/23 11:19 AM
 */
public class JsonUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    public JsonUsernamePasswordAuthenticationFilter() {
        super();
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String contentType = request.getContentType();
        logger.info("login contentType: "+contentType);
        if (MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(contentType) || MediaType.APPLICATION_JSON_UTF8_VALUE.equalsIgnoreCase(contentType)) {
            String username = null;
            String password = null;
            String code = null;
            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(request.getInputStream())))) {
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                String body = stringBuilder.toString();
                logger.info("login request body : " + body);
                if (StringUtils.isNotBlank(body)) {
                    ObjectMapper objectMapper = new ObjectMapper();
                    Map map = objectMapper.readValue(body, Map.class);
                    username = (String) map.get(getUsernameParameter());
                    password = (String) map.get(getPasswordParameter());
                    code = (String) map.get("code");
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            if (username == null) {
                username = "";
            }
            if (password == null) {
                password = "";
            }
            if (code == null){
                code = "";
            }
            username = username.trim();

            CaptchaUsernamePasswordAuthenticationToken authRequest = new CaptchaUsernamePasswordAuthenticationToken(
                    code,username, password);

            // Allow subclasses to set the "details" property
            setDetails(request, authRequest);

            return this.getAuthenticationManager().authenticate(authRequest);
        } else {
            return super.attemptAuthentication(request, response);
        }
    }
}
